/**
 * 图片加载优化工具
 */

// 图片懒加载指令
export const lazyLoad = {
  mounted(el, binding) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = binding.value;
          img.classList.remove('lazy');
          observer.unobserve(img);
        }
      });
    });

    observer.observe(el);
  }
};

// 图片预加载
export const preloadImage = (src) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = src;
  });
};

// 批量预加载图片
export const preloadImages = (srcs) => {
  return Promise.all(srcs.map(src => preloadImage(src)));
};

// 图片压缩（客户端）
export const compressImage = (file, quality = 0.8, maxWidth = 800) => {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = () => {
      // 计算新的尺寸
      let { width, height } = img;
      if (width > maxWidth) {
        height = (height * maxWidth) / width;
        width = maxWidth;
      }
      
      canvas.width = width;
      canvas.height = height;
      
      // 绘制图片
      ctx.drawImage(img, 0, 0, width, height);
      
      // 转换为blob
      canvas.toBlob(resolve, 'image/jpeg', quality);
    };
    
    img.src = URL.createObjectURL(file);
  });
};

// 获取图片尺寸
export const getImageSize = (src) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      resolve({
        width: img.naturalWidth,
        height: img.naturalHeight
      });
    };
    img.src = src;
  });
};

// 图片占位符生成
export const generatePlaceholder = (width, height, text = '图片加载中...') => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  
  canvas.width = width;
  canvas.height = height;
  
  // 绘制背景
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, width, height);
  
  // 绘制文字
  ctx.fillStyle = '#999';
  ctx.font = '14px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(text, width / 2, height / 2);
  
  return canvas.toDataURL();
};

// 图片错误处理
export const handleImageError = (event, fallbackSrc = '/default-product.jpg') => {
  const img = event.target;
  if (img.src !== fallbackSrc) {
    img.src = fallbackSrc;
  }
};

// 图片加载状态管理
export class ImageLoader {
  constructor() {
    this.cache = new Map();
    this.loading = new Set();
  }

  async load(src, options = {}) {
    const { 
      fallback = '/default-product.jpg',
      timeout = 10000,
      retry = 3 
    } = options;

    // 检查缓存
    if (this.cache.has(src)) {
      return this.cache.get(src);
    }

    // 检查是否正在加载
    if (this.loading.has(src)) {
      return new Promise((resolve, reject) => {
        const checkLoaded = () => {
          if (this.cache.has(src)) {
            resolve(this.cache.get(src));
          } else if (!this.loading.has(src)) {
            reject(new Error('Image load failed'));
          } else {
            setTimeout(checkLoaded, 100);
          }
        };
        checkLoaded();
      });
    }

    this.loading.add(src);

    try {
      const img = await this.loadImage(src, timeout, retry);
      this.cache.set(src, img);
      this.loading.delete(src);
      return img;
    } catch (error) {
      this.loading.delete(src);
      
      // 尝试加载fallback
      if (fallback && fallback !== src) {
        try {
          const fallbackImg = await this.loadImage(fallback, timeout, retry);
          this.cache.set(src, fallbackImg);
          return fallbackImg;
        } catch (fallbackError) {
          console.error('Fallback image also failed:', fallbackError);
        }
      }
      
      throw error;
    }
  }

  async loadImage(src, timeout, retry) {
    let lastError;
    
    for (let i = 0; i < retry; i++) {
      try {
        return await Promise.race([
          preloadImage(src),
          new Promise((_, reject) => 
            setTimeout(() => reject(new Error('Timeout')), timeout)
          )
        ]);
      } catch (error) {
        lastError = error;
        if (i < retry - 1) {
          await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        }
      }
    }
    
    throw lastError;
  }

  clearCache() {
    this.cache.clear();
  }

  removeFromCache(src) {
    this.cache.delete(src);
  }
}

// 创建全局图片加载器实例
export const imageLoader = new ImageLoader(); 